package org.jsbd.boss.action;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.jsbd.boss.common.DataGridModel;
import org.jsbd.boss.common.ResponseUtils;
import org.jsbd.boss.dao.IRetentTimesDao;
import org.jsbd.boss.domian.ChannelApkInfo;
import org.jsbd.boss.domian.ChannelProvinceInfo;
import org.jsbd.boss.domian.ProvinceInfo;
import org.jsbd.boss.domian.channel.ChannelApkConfig;
import org.jsbd.boss.domian.channel.ChannelRetentConfig;
import org.jsbd.boss.domian.channel.RetentTimesConfig;
import org.jsbd.boss.service.IChannelApkInfoService;
import org.jsbd.boss.service.impl.ChannelConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/channelconfig")
public class ChannelConfigController {
	public static final Logger LOGGER = LoggerFactory.getLogger(ChannelConfigController.class);

	@Autowired
	private ChannelConfigService channelConfigService;
	@Autowired
	private IRetentTimesDao retentTimesDao;

	@Resource
	private IChannelApkInfoService channelApkInfoService;

	@RequestMapping(value = "/provinceconfigList", method = RequestMethod.GET)
	public String provinceconfigList(Model model) {
		return "channelapk/provinceconfigList";
	}


	// 省份查询展示接口
	@RequestMapping(value = "/{mark}/provinceUpdate")
	public String updateProvince(@PathVariable String mark, Model model) {
		LOGGER.info("updateProvince,mark is [{}]", mark);
		ChannelApkInfo channelApkInfo = channelConfigService.getProvinceByMark(mark);

		if (channelApkInfo != null && StringUtils.isNotBlank(channelApkInfo.getProvinceIds())) {
			String province = channelApkInfo.getProvinceIds();
			List<String> list = Arrays.asList(province.split(","));
			model.addAttribute("openProvinceList", list);
		}
		List<ProvinceInfo> provinceList = channelConfigService.getProvinceInfoList();
		model.addAttribute("provinceList", provinceList);
		return "channelapk/addProvince";
	}

	@RequestMapping(value = "/saveProvince", method = RequestMethod.POST)
	public void saveProvince(Model model, String mark, String openProvince, HttpServletResponse response) {
		if (mark == null) {
			ResponseUtils.responseFailure(response);
		}
		// 更新操作
		channelConfigService.updateProvinceByMark(mark, openProvince);
		ResponseUtils.responseSuccess(response);
	}


	@ResponseBody
	@RequestMapping(value = "/provinceDelete", method = RequestMethod.GET)
	public void provincedelete(String mark, String provinceid, String privinceid, HttpServletResponse response) {
		channelConfigService.deleteProvinceBymarkAndid(mark, provinceid);
		ResponseUtils.responseSuccess(response);
	}

	@RequestMapping(value = "/retentList")
	@ResponseBody
	public Map<String, Object> retentPageList(DataGridModel model, ChannelRetentConfig form) {
		Map<String, Object> map = new HashMap<String, Object>(); 
		String mark = form.getMark();
		if (StringUtils.isBlank(mark)) {
			return map;
		}
		
		if (StringUtils.isNotBlank(mark)) {
			String[] marks = mark.split(" ");
			List<String> keywords = new ArrayList<>();
			for (String keyword : marks) {
				keywords.add(keyword);
			}
			form.setKeywords(keywords);
		}
		
		List<ChannelRetentConfig> retrntList = channelConfigService.getRetentBymarkforPage(mark);
		map.put("rows", retrntList);
		return map;
	}

	@RequestMapping(value = "/retentList", method = RequestMethod.GET)
	public String retentPageList(Model model, HttpServletResponse response) {
		return "channelconfig/retentConfig";
	}

	@RequestMapping(value = "/saveRetent")
	public void saveRetent(@RequestBody ChannelRetentConfig[] list, HttpServletResponse response) {

		channelConfigService.saveChannelRetentConfig(Arrays.asList(list));

		ResponseUtils.responseSuccess(response);
	}

	@RequestMapping(value = "/deleteRetent")
	public void deleteRetent(@RequestBody ChannelRetentConfig form, HttpServletResponse response) {

		channelConfigService.deleteChannelRetentConfig(form);

		ResponseUtils.responseSuccess(response);
	}
	
	@RequestMapping(value = "/batchDelete", method = RequestMethod.POST)
	public void deleteRetentBatch(@RequestBody List<Map> list, HttpServletResponse response) {
		for (Map map : list) {
			ChannelRetentConfig crc = new ChannelRetentConfig();
			crc.setRetentRate(Double.valueOf(String.valueOf(map.get("retentRate"))));
			crc.setRetentDay(Integer.valueOf(String.valueOf(map.get("retentDay"))));
			crc.setExetimes(Integer.valueOf(String.valueOf(map.get("exetimes"))));
			crc.setMark(String.valueOf(map.get("mark")));
			crc.setPriority(Integer.valueOf(String.valueOf(map.get("priority"))));
			channelConfigService.deleteChannelRetentConfig(crc);
		}
		
		ResponseUtils.responseSuccess(response);
	}

	// 基本配置查询展示接口
	@RequestMapping(value = "/provinceconfigList", params = "json")
	@ResponseBody
	public Map<String, Object> provinceconfigPageList(DataGridModel model, ChannelProvinceInfo form) {
		form = (form == null ? new ChannelProvinceInfo() : form);
		form.setPageInfo(model);
		Map<String, Object> map = channelConfigService.selectConfigPageListMap(form);
		List<ChannelApkInfo> configList = (List<ChannelApkInfo>) map.get("rows");
		map.put("rows", configList);
		return map;
	}

	// 基本配置查询展示接口
	@RequestMapping(value = "/provinceRateUpdate")
	@ResponseBody
	public int provinceRateUpdate(HttpServletRequest request, HttpServletResponse resp) {
		ChannelProvinceInfo form = new ChannelProvinceInfo();
		form.setMark(request.getParameter("mark"));
		form.setProvinceid(request.getParameter("provinceid"));
		form.setProvinceRate(Integer.parseInt(request.getParameter("provinceRate")));
		return channelConfigService.updateProvinceRate(form);
	}


	@RequestMapping(value = "resetTimes")
	public void resetTimes(String mark, HttpServletResponse response) {
		try {
			ChannelRetentConfig channelRetentConfig = new ChannelRetentConfig();
			channelRetentConfig.setMark(mark);
			channelRetentConfig.setExetimes(1);
			channelConfigService.updateConfig(channelRetentConfig);
			ResponseUtils.responseSuccess(response);
		} catch (Exception e) {
			LOGGER.error("删除apk出错", e);
			ResponseUtils.responseFailure(response);
		}
	}


	@RequestMapping(value = "resetPri")
	public void resetPri(String mark, HttpServletResponse response) {
		try {
			ChannelRetentConfig channelRetentConfig = new ChannelRetentConfig();
			channelRetentConfig.setMark(mark);
			channelRetentConfig.setPriority(0);
			channelConfigService.updateConfig(channelRetentConfig);
			ResponseUtils.responseSuccess(response);
		} catch (Exception e) {
			LOGGER.error("删除apk出错", e);
			ResponseUtils.responseFailure(response);
		}
	}

	@RequestMapping(value = "resetBrush")
	public void resetBrush(String mark, HttpServletResponse response) {
		try {
			ChannelRetentConfig channelRetentConfig = new ChannelRetentConfig();
			channelRetentConfig.setMark(mark);
			channelRetentConfig.setBrushRate(0D);
			channelConfigService.updateConfig(channelRetentConfig);
			ResponseUtils.responseSuccess(response);
		} catch (Exception e) {
			LOGGER.error("删除apk出错", e);
			ResponseUtils.responseFailure(response);
		}
	}


	@RequestMapping(value = "/retentExecTimesList")
	@ResponseBody
	public Map<String, Object> retentExecTimesList(DataGridModel model, ChannelRetentConfig form) {
		Map<String, Object> map = new HashMap<>();
		String mark = form.getMark();
		if (StringUtils.isBlank(mark)) {
			return map;
		}
		ChannelApkConfig apkConfig = channelApkInfoService.selectChannelApkConfig(mark);
		if(apkConfig == null){
			return map;
		}
		RetentTimesConfig config = new RetentTimesConfig();
		config.setApkId(apkConfig.getId());
		List<RetentTimesConfig> configList = retentTimesDao.selectConfigList(config);
		map.put("rows", configList);
		return map;
	}

	@RequestMapping(value = "/retentExecTimesList", method = RequestMethod.GET)
	public String retentExecTimesList(Model model, String mark) {
		Map<String, Object> map = new HashMap<>();
		ChannelApkConfig apkConfig = channelApkInfoService.selectChannelApkConfig(mark);
		RetentTimesConfig config = new RetentTimesConfig();
		config.setApkId(apkConfig.getId());
		List<RetentTimesConfig> configList = retentTimesDao.selectConfigList(config);
		map.put("rows", configList);
		model.addAllAttributes(map);
		model.addAttribute("mark",mark);
		return "channelconfig/retentExecTimesList";
	}


	@RequestMapping(value = "/saveRetentExecTimes")
	public void saveRetentExecTimes(@RequestBody RetentTimesConfig[] list, HttpServletResponse response) {


		if(list == null || list.length ==0){
			return;
		}
		ChannelApkConfig apkConfig = channelApkInfoService.selectChannelApkConfig(list[0].getMark());
		if(apkConfig == null){
			ResponseUtils.responseFailure(response);
		}else{
			List<RetentTimesConfig> configList = Arrays.asList(list);
			for(RetentTimesConfig config : configList){
				config.setApkId(apkConfig.getId());
			}
			channelConfigService.saveRetentExecTimesConfig(configList);

			ResponseUtils.responseSuccess(response);
		}
	}


	@RequestMapping(value = "/batchDeleteTimes", method = RequestMethod.POST)
	public void batchDeleteTimes(@RequestBody List<RetentTimesConfig> retentTimesConfigs, HttpServletResponse response) {
		String times = JSONObject.toJSONString(retentTimesConfigs);
		List<RetentTimesConfig> configList = JSONObject.parseArray(times, RetentTimesConfig.class);
		channelConfigService.batchDeleteTimes(configList);
		ResponseUtils.responseSuccess(response);
	}

}
